package com.heer.gymnasium.module.store.views;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.SignHelper;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.module.login.views.LoginActivity;
import com.heer.gymnasium.module.map.views.MapShowActivity;
import com.heer.gymnasium.module.store.beans.StoreBean;
import com.heer.gymnasium.module.store.beans.StoreResponseBean;
import com.heer.gymnasium.util.StringUtils;
import com.heer.gymnasium.util.SystemUtils;
import com.heer.imagepick.DensityUtils;
import com.zhihuiyun.library.view.MyGridView;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by zy on 2018/1/19.
 */

public class StoreDetailActivity extends BaseActivity {
    private final int RES_ID_ROOT_LAYOUT = R.layout.layout_store_details;

    private final int RES_ID_DESCRIBE = R.id.layout_store_details_describe_content_tv;
    private final int RES_ID_DESCRIBE_MORE = R.id.layout_store_details_more_fl;
    private final int RES_ID_DESCRIBE_MORE_IV = R.id.layout_store_details_more_iv;

    private final int RES_ID_SERVICE_CONTENT = R.id.layout_store_details_service_content_gv;
    private final int RES_ID_EVALUATE = R.id.layout_store_details_evaluate_gv;

    private final static int RES_ID_PHONE = R.id.layout_store_details_phone_fl;
    private final static int RES_ID_ADDRESS_PANEL = R.id.layout_store_details_address_ll;
    private final static int RES_ID_ADDRESS = R.id.layout_store_details_address_tv;
    private final static int RES_ID_OPEN_TIME = R.id.layout_store_details_open_time_tv;

    private final static int DRAWABLE_COLLECT_WHITE = R.drawable.ic_collect;
    private final static int DRAWABLE_COLLECT_ORANGE = R.drawable.ic_collect_foucs;

    @BindView(RES_ID_DESCRIBE)
    TextView describe;
    @BindView(RES_ID_DESCRIBE_MORE_IV)
    ImageView moreAnchor;
    @BindView(RES_ID_SERVICE_CONTENT)
    MyGridView serviceContentGrid;
    @BindView(RES_ID_EVALUATE)
    MyGridView evaluateGrid;
    @BindView(RES_ID_ADDRESS)
    TextView tvAddress;
    @BindView(RES_ID_OPEN_TIME)
    TextView tvOpenTime;

    private String storeId;
    private Float la, lo;


    private ArrayList<String> serviceContentArr, evaluateArr;
    private ArrayAdapter<String> serviceAdapter, evaluateAdapter;

    private StoreDetailActivity $this;
    private String phone;
    private boolean canClick = true;
    private StoreBean bean;

    @Override
    protected void init() {
        super.init();
        $this = this;
        setContentView(RES_ID_ROOT_LAYOUT);
        storeId = getIntent().getStringExtra(EXTRA_ID);
        if (TextUtils.isEmpty(storeId)) {
            ToastUtil.show($this, "未找到店铺");
            finish();
            return;
        }
    }

    @Override
    protected void initView() {
        super.initView();
        titleUtils.setRightImage(R.drawable.ic_collect, 20);
        titleUtils.setRightOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doFocus();
            }
        });
        moreAnchor.setVisibility(View.GONE);
        describe.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (describe.getLineCount() > 0) {
                    if (describe.getLayout().getEllipsisCount(describe.getLineCount() - 1) > 0) {
                        moreAnchor.setVisibility(View.VISIBLE);
                    } else if (describe.getMaxLines() == 3) {
                        moreAnchor.setVisibility(View.GONE);
                    }
                }
            }
        });

        serviceContentArr = new ArrayList<>();
        serviceContentGrid.setAdapter(serviceAdapter = new ArrayAdapter<String>($this, RES_ID_ROOT_LAYOUT, serviceContentArr) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                TextView textView = new TextView($this);
                textView.setBackgroundResource(R.drawable.yellow_button_bg);
                textView.setTextColor(Color.WHITE);
                textView.setTextSize(13);
                textView.setText(serviceContentArr.get(position));
                textView.setGravity(Gravity.CENTER);
                textView.setPadding(10, 5, 10, 5);
                textView.setMaxLines(1);
                return textView;
            }
        });
        serviceContentGrid.setHorizontalSpacing(DensityUtils.dip2px($this, 5));
        serviceContentGrid.setVerticalSpacing(DensityUtils.dip2px($this, 5));

        evaluateArr = new ArrayList<>();
        evaluateGrid.setAdapter(evaluateAdapter = new ArrayAdapter<String>($this, RES_ID_ROOT_LAYOUT, evaluateArr) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                TextView textView = new TextView($this);
                textView.setBackgroundResource(R.drawable.yellow_border);
                textView.setTextColor(Color.BLACK);
                textView.setTextSize(13);
                textView.setText(evaluateArr.get(position));
                textView.setGravity(Gravity.CENTER);
                textView.setPadding(10, 5, 10, 5);
                textView.setMaxLines(1);
                return textView;
            }
        });
        evaluateGrid.setHorizontalSpacing(DensityUtils.dip2px($this, 5));
        evaluateGrid.setVerticalSpacing(DensityUtils.dip2px($this, 5));
    }

    @Override
    protected void loadData() {
        super.loadData();
        getStoreDetailById(storeId);
    }

    @OnClick({RES_ID_DESCRIBE, RES_ID_DESCRIBE_MORE})
    public void onDescribeMoreClick() {
        if (describe.getMaxLines() == 3) {
            describe.setMaxLines(Integer.MAX_VALUE);
            RotateAnimation rotateAnimation = new RotateAnimation(0.0f, +180.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            rotateAnimation.setDuration(60);
            rotateAnimation.setFillAfter(true);
            rotateAnimation.setRepeatCount(0);
            moreAnchor.startAnimation(rotateAnimation);
        } else {
            describe.setMaxLines(3);
            RotateAnimation rotateAnimation = new RotateAnimation(+180.0f, 0.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            rotateAnimation.setDuration(60);
            rotateAnimation.setFillAfter(true);
            rotateAnimation.setRepeatCount(0);
            moreAnchor.startAnimation(rotateAnimation);
        }
    }

    private void doFocus() {
        if (canClick) {
            canClick = false;
            mAppHelper.apiService().doFocus(FOCUS_TYPE_STORE, storeId).enqueue(new BaseCallback<ApiResponse<String>>() {
                @Override
                public void onSuccess(Call<ApiResponse<String>> call, Response<ApiResponse<String>> response) {
                    canClick = true;
                    ToastUtil.show($this, response.body().getMsg());
                    loadData();
                }

                @Override
                public void onTokenTimeOut() {
                    canClick = true;
                    LoginActivity.logout($this, LoginActivity.TIME_OUT);
                }

                @Override
                public void onError(Call<ApiResponse<String>> call, Throwable t) {
                    canClick = true;
                }
            });
        }
    }

    @OnClick(RES_ID_PHONE)
    public void onDial() {
        SystemUtils.dialNumber($this, phone);
    }

    @OnClick(RES_ID_ADDRESS_PANEL)
    public void toMap() {
        MapShowActivity.startActvity($this, bean);
    }


    public static void startActivity(Context context, String id) {
        Intent intent = new Intent(context, StoreDetailActivity.class);
        intent.putExtra(EXTRA_ID, id);
        context.startActivity(intent);
    }

    private void getStoreDetailById(String sid) {
        mAppHelper.apiService().getStadiumInfo(sid).enqueue(new BaseCallback<ApiResponse<StoreResponseBean.Info>>() {
            @Override
            public void onSuccess(Call<ApiResponse<StoreResponseBean.Info>> call, Response<ApiResponse<StoreResponseBean.Info>> response) {
                initStadiumInfo(StoreBean.dataChange(response.body().getData()));
            }

            @Override
            public void onTokenTimeOut() {
                LoginActivity.logout($this, LoginActivity.TIME_OUT);
            }
        });
    }

    private void initStadiumInfo(StoreBean storeBean) {
        bean = getBean(storeBean);
        titleUtils.setTitleText(storeBean.getStadiumname());
        phone = storeBean.getStadiumtel();
        describe.setText(storeBean.getStadiumcontent());
        tvAddress.setText(storeBean.getStadiumaddress());
        la = StringUtils.toFloat(storeBean.getLa());
        lo = StringUtils.toFloat(storeBean.getLo());
        tvOpenTime.setText(storeBean.getStadiumbusinesstime());

        if (TextUtils.equals("0", storeBean.getFocus_id())) {
            titleUtils.setRightImage(DRAWABLE_COLLECT_WHITE, 15);
        } else {
            titleUtils.setRightImage(DRAWABLE_COLLECT_ORANGE, 15);
        }
        serviceContentArr.clear();
        evaluateArr.clear();
        for (int i = 0, max = storeBean.getServer().size(); i < max; i++) {
            String showTag = storeBean.getServer().get(i).getName();
            serviceContentArr.add(showTag);
        }

        for (int i = 0, max = storeBean.getTag_list().size(); i < max; i++) {
            String showTag = storeBean.getTag_list().get(i).getName();
            evaluateArr.add(showTag);
        }
        serviceAdapter.notifyDataSetChanged();
        evaluateAdapter.notifyDataSetChanged();
    }

    private StoreBean getBean(StoreBean storeBean) {
        StoreBean bean = new StoreBean();
        bean.setSid(storeBean.getSid());
        bean.setStadiumname(storeBean.getStadiumname());
        bean.setEval(storeBean.getEval());
        bean.setLa(storeBean.getLa());
        bean.setLo(storeBean.getLo());
        return bean;
    }
}
